#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include "../../../source/sgl.h"
#include "./background.h"

sgl_color_t *linux_fb;

sgl_img_t bg_img = {.bitmap = bg_test, .width = 240, .height = 320,};

extern void demo_setup(void *data);

int stdout_device(char *str)
{
    return printf("%s\n", str);
}

int main()
{
    int fbfd = 0;
    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;
    long int screensize = 0;

    // Open the file for reading and writing
    fbfd = open("/dev/fb0", O_RDWR);
    if (fbfd == -1) {
        perror("Error: cannot open framebuffer device");
        exit(1);
    }
    printf("The framebuffer device was opened successfully.\n");

    // Get fixed screen information
    if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo) == -1) {
        perror("Error reading fixed information");
        exit(2);
    }

    // Get variable screen information
    if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo) == -1) {
        perror("Error reading variable information");
        exit(3);
    }
    if (vinfo.bits_per_pixel != SGL_CONFIG_PANEL_PIXEL_DEPTH) {
        perror("color width not match, please update SGL_CONFIG_PANEL_PIXEL_DEPTH");
        exit(4);
    }

    printf("%dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);

    // Figure out the size of the screen in bytes
    screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;

    // Map the device to memory
    linux_fb = (sgl_color_t *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0);
    if (linux_fb == NULL) {
        perror("Error: failed to map framebuffer device to memory");
        exit(4);
    }
    linux_fb += vinfo.xoffset + vinfo.yoffset * vinfo.yres_virtual;
    printf("The framebuffer device was mapped to memory successfully.\n");

    sgl_device_panel_t linuxfb_panel = {
                                    .framebuffer = linux_fb, 
                                    .xres = vinfo.xres,
                                    .yres = vinfo.yres,
                                    .xres_virtual = vinfo.xres_virtual,
                                    .yres_virtual = vinfo.yres_virtual,
                                    };

    sgl_device_stdout_t stdout_dev = {
                                    .put = stdout_device,
                                    };
    
    sgl_device_register(&linuxfb_panel, NULL);
    
    sgl_device_stdout_register(&stdout_dev);

    sgl_init();

    SGL_LOG_INFO("start linuxfb sgl...");

    sgl_obj_t *main_page = sgl_page_create();

    sgl_page_set_background(main_page, &bg_img);

    sgl_page_set_active(main_page);

    demo_setup(main_page);

    while (1)
    {
        sgl_tick_inc(5);
        sgl_task_handler();
        usleep(10000);
    }

    munmap(linux_fb, screensize);
    close(fbfd);
    return 0;
}
